package shorturl.generator.string;


import shorturl.IStringGenerator;

import java.util.Random;

/**
 * 随机字符串生成器
 */
public class RandomStringGenerator implements IStringGenerator {

    public static char[] VALID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    private static Random random = new Random(System.currentTimeMillis());
    /**
     * 短链接字符串长度 默认6
     */
    private int length = 6;

    public RandomStringGenerator(){

    }

    public RandomStringGenerator(int length){
        setLength(length);
    }

    @Override
    public void setLength(int length) {
        this.length = length;
    }

    /**
     * 这里的实现不考虑url，直接生成随机字符串即可，这个算法如果容量比较大的时候，性能会变低，因此要根据使用情况选择合适的长度
     * @param url 原始链接
     * @return
     */
    @Override
    public String generate(String url) {
        char[] shorterChars = new char[length];
        int seed = random.nextInt(Integer.MAX_VALUE);
        for (int i = 0; i < length; i++) {
            shorterChars[i] = VALID_CHARS[seed % VALID_CHARS.length];
            seed = random.nextInt(Integer.MAX_VALUE) % VALID_CHARS.length;
        }
        return new String(shorterChars);
    }
}
